<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/20
 * Time: 16:39
 */
namespace app\cron\service;

use app\model\Category;

class CategoryService
{
    private static $category;

    public function __construct()
    {
        self::$category = new Category();
    }

    public static function matchCategory()
    {
        new self;
        $category = [];
        $url = 'https://blog.csdn.net/sinat_28156831';
        $html = curlCall($url, '', 'GET');
        $rule = '/<a href="https:\/\/blog.csdn.net\/sinat_28156831\/article\/category\/(.*?)">(.*?)<span/ies';
        $res = preg_match_all($rule, $html, $match);
        if (!empty($res)) {
            foreach ($match[2] as $key => $item) {
                $str = explode('"', $match[0][$key]);
                $category[$match[1][$key]] = [
                    'title' => trim($item),
                    'url' => $str[1],
                ];
            }
        }
        self::_insertIntoCategory($category);
        echo "ok";
    }

    private static function _insertIntoCategory($data)
    {
        foreach ($data as $key => $item) {
            $search_data = [
                'csdn_id' => $key,
            ];
            $info = self::$category->getOneInfo($search_data, 'id');
            $insert_data = [
                'name' => $item['title'],
                'csdn_id' => $key,
                'csdn_url' => $item['url'],
                'type' => 0,
            ];
            if (empty($info)) {
                $insert_data['create_time'] = date('Y-m-d H:i:s');
                self::$category->insertData($insert_data);
            } else {
                $where = ['id' => $info['id']];
                $insert_data['update_time'] = date('Y-m-d H:i:s');
                self::$category->updateData($where, $insert_data);
            }
        }
        return true;
    }

}